const createError = require('http-errors');
const express = require('express');
const cors = require("cors");
const path = require('path');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const session = require("express-session");

const {verifyToken,errorToken} = require('./middleware/auth');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');

var app = express();
app.use(cors());
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());

// app.use(
//   session({
//       secret: 'keyboard cat',
//       resave: false,
//       saveUninitialized: true,
//       cookie: { 
//         maxAge: 60000
//       }
//   })
// )

//连接数据库
require("./plugins/db")(app);

//托管静态资源
app.use(express.static(path.join(__dirname, 'public')));

//解析token获取用户信息
app.use(verifyToken);

app.use('/api', indexRouter);
app.use('/api/user', usersRouter);

//当token失效返回提示信息
app.use(errorToken);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  res.status.send({errCode:"1",msg:"页面不存在"});
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
});

module.exports = app;
